package com.shun.base.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shun.base.mapper.ShunDictDataMapper;
import com.shun.base.service.IShunDictDataService;
import com.shun.base.vo.ShunDictData;
import com.shun.common.R;
import com.shun.common.page.ShunPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典数据表 服务实现类
 * </p>
 *
 * @author clever
 * @since 2021-10-03
 */
@Slf4j
@Service
public class ShunDictDataServiceImpl extends ServiceImpl<ShunDictDataMapper, ShunDictData> implements IShunDictDataService {

    private final static String ERR_DICT_ADD = "新增字典数据失败";

    private final static String ERR_DICT_EDIT = "更新字典数据失败";

    private final static String ERR_DICT_DEL = "删除字典数据失败";

    @Override
    public R getDictData(String oldDictType) {
        String dictType = oldDictType.substring(5);
        log.debug("dictType:{}",dictType);
        QueryWrapper<ShunDictData> shunDictDataQueryWrapper = new QueryWrapper<>();
        shunDictDataQueryWrapper.lambda().eq(ShunDictData::getDictType,dictType).eq(ShunDictData::getStatus,"0");
        List<Map<String,Object>> dictList = list(shunDictDataQueryWrapper).stream().map(d -> {
            Map<String,Object> dictMap  = new HashMap<>();
            dictMap.put("key",d.getDictLabel());
            dictMap.put("value",d.getDictValue());
            return dictMap;
        }).collect(Collectors.toList());
        return R.suc(dictList);
    }

    @Override
    public R addDictData(ShunDictData dictData) {
        log.debug("dictData:{}",dictData);
        String userId = StpUtil.getLoginIdAsString();
        dictData.setCreateUser(userId);
        return save(dictData)?R.suc():R.error(ERR_DICT_ADD);
    }

    @Override
    public R editDictData(ShunDictData dictData) {
        log.debug("dictData:{}",dictData);
        UpdateWrapper<ShunDictData> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("data_id",dictData.getDataId());
        return update(dictData,updateWrapper)?R.suc():R.error(ERR_DICT_EDIT);
    }

    @Override
    public R delDictData(String dictId) {
        log.debug("dictId:{}",dictId);
        return removeById(dictId)?R.suc():R.error(ERR_DICT_DEL);
    }

    @Override
    public R pageDict(ShunPage<ShunDictData> page) {
        log.debug("page:{}",page);
        QueryWrapper<ShunDictData> queryWrapper = new QueryWrapper<>();
        IPage<ShunDictData> dictDataIPage = page(page.toPage(),queryWrapper.isNotNull("data_id"));
        return R.suc(dictDataIPage);
    }
}
